package cn.ijero.composeui.page.advanced.tabpager

import android.content.Context
import android.content.Intent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.*
import androidx.compose.material.TabRowDefaults.tabIndicatorOffset
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import cn.ijero.composeui.base.BaseActivity
import cn.ijero.composeui.page.advanced.welcome.WelcomePager
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.launch

class TabPagerActivity : BaseActivity() {

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, TabPagerActivity::class.java)
            context.startActivity(starter)
        }
    }

    @Composable
    override fun RenderContent() {
        RootLayout()
    }

}

@OptIn(ExperimentalPagerApi::class)
@Composable
private fun RootLayout() {
    Box {
        val items = listOf("Android","IOS","Windows","MacOS")
        var tabStr by remember {
            mutableStateOf("Android")
        }
        val state = rememberPagerState(0)
        val scope = rememberCoroutineScope()
        WelcomePager(items, state)
        // TabRow/ScrollableTabRow
        TabRow(
            selectedTabIndex = items.indexOf(tabStr),
            modifier = Modifier.fillMaxWidth(),
            indicator = { tabIndicator->
                TabRowDefaults.Indicator(
                    Modifier.tabIndicatorOffset(tabIndicator[items.indexOf(tabStr)])
                )
            },
            divider = {}
        ) {
            items.forEachIndexed { index, title ->
                val selected = index == items.indexOf(tabStr)
                Tab(selected = selected, onClick = {
                    tabStr = items[index]
                    scope.launch {
                        state.scrollToPage(index)
                    }
                }, text = {
                    Text(text = items[index])
                })
            }
        }
        tabStr = items[state.currentPage]
    }
}


@Preview(showBackground = true)
@Composable
private fun DefaultPreview() {
    RootLayout()
}